package com.loyal.helper;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.view.Gravity;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.loyal.R;
import com.loyal.dialog.MessageDialog;
import com.loyal.impl.ScrollingTextViewTouchListener;

import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;

public class DialogHelper {
    private static final String TAG = DialogHelper.class.getName();
    private static ConcurrentHashMap<String, Dialog> dialogMap;

    static {
        dialogMap = new ConcurrentHashMap<>();
    }

    public static void showInActivity(Activity activity, CharSequence content) {
        showInActivity(activity, content, false);
    }

    /**
     * @param activity UIActivity
     * @param content  message  String error = null == e ? "" : ErrorUtil.getError(e);
     *                 String message= ResUtil.replaceText(sequence) + (TextUtils.isEmpty(error) ? "" : "\n" + error)
     * @param isFinish 是否finish当前页面
     */
    public static void showInActivity(Activity activity, CharSequence content, final boolean isFinish) {
        if (null == activity) return;
        activity.runOnUiThread(() -> {
            MessageDialog alertDialog = createMessageDialog(activity, content);
            if (null == alertDialog) return;
            if (isFinish) alertDialog.setCancelable(false);
            alertDialog.setCanceledOnTouchOutside(!isFinish);
            alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", (dialog, which) -> {
                dialog.dismiss();
                if (isFinish) {
                    activity.finish();
                }
            });
            alertDialog.show();
        });
    }

    public static @Nullable
    MessageDialog createMessageDialog(@Nullable Context context, CharSequence message) {
        if (null == context) return null;
        String key = context.getClass().getName();
        MessageDialog dialog = get(key);
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
        }
        dialog = new MessageDialog.Builder(context, R.style.AppTheme_Dialog)
                .setMessage(message).create();
        return dialog;
    }

    @SuppressLint("ClickableViewAccessibility")
    public static <T extends Dialog> void scroll(T dialog) {
        if (null == dialog) return;
        TextView messageView = dialog.findViewById(android.R.id.message);
        if (null != messageView) {
            messageView.setMovementMethod(ScrollingMovementMethod.getInstance());
            messageView.setOnTouchListener(new ScrollingTextViewTouchListener());
        }
    }

    /**
     * @Override public void show() {
     * Window window=getWindow();
     * window.setFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
     * super.show();
     * fullScreenShowDialog(window);
     * }
     */
    public static void fullScreenShowDialog(@Nullable Window window) {
        if (null == window) return;
        UIHelper.fullScreenImmersive(window);
        window.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
    }

    /**
     * @param window     dialog.getWindow()
     * @param fullScreen full in WindowScreen
     */
    public static void showFullScreen(@Nullable Window window, boolean fullScreen) {
        if (null == window) return;
        window.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
        if (fullScreen) UIHelper.fullScreenImmersive(window);
    }

    public static <T extends Dialog> void add(@NonNull String key, T dialog) {
        if (null == dialog) return;
        dialogMap.put(key, dialog);
    }

    /**
     * @param context 注意和AlertDialog.Builder(context)使用的必须是同一个，
     *                且不能用dialog.getContext(),
     *                不然对象不一致
     */
    public static @Nullable
    <T extends Dialog> T get(@Nullable Context context) {
        if (null == context) return null;
        String key = context.getClass().getName();
        return get(key);
    }

    @SuppressWarnings("unchecked")
    public static @Nullable
    <T extends Dialog> T get(String key) {
        if (TextUtils.isEmpty(key)) return null;
        return (T) dialogMap.get(key);
    }

    /**
     * @param context 注意和AlertDialog.Builder(context)使用的必须是同一个，
     *                且不能用dialog.getContext(),对象不一致
     */
    public static void remove(Context context) {
        if (null == context) return;
        String key = context.getClass().getName();
        remove(key);
    }

    public static void remove(String key) {
        if (TextUtils.isEmpty(key)) return;
        Dialog dialog = dialogMap.remove(key);
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    /**
     * @param window dialog.getWindow()
     */
    public static void showPositionCenter(Window window) {
        showPosition(window, Gravity.CENTER);
    }

    /**
     * @param gravity 显示位置
     */
    public static void showPosition(Window window, int gravity) {
        if (null == window)
            return;

        WindowManager.LayoutParams attributes = window.getAttributes();
        attributes.gravity = gravity;
        window.setAttributes(attributes);
    }

    public static int size() {
        return dialogMap.size();
    }

    public static void dismiss() {
        Iterator<Dialog> it = dialogMap.values().iterator();
        while (it.hasNext()) {
            Dialog dialog = it.next();
            if (null != dialog && dialog.isShowing()) {
                dialog.dismiss();
            }
            it.remove();
        }
        dialogMap.clear();
    }
}
